package bsk;

/**
 * @author
 */
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.*;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.jce.PKCS10CertificationRequest;
import org.bouncycastle.x509.X509V3CertificateGenerator;

/**
 *
 */
public class ReqGen {

    /**
     *
     */
    public static X509Certificate getNewCert(KeyPair pair) throws CertificateParsingException, InvalidKeyException, CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, Exception {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setIssuerDN(new X500Principal("CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=PL"));
        certGen.setNotBefore(new Date(System.currentTimeMillis()));
        certGen.setNotAfter(new Date(System.currentTimeMillis() + 7 * 24 * 3600000));// 
        //certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject());
        certGen.setSubjectDN(new X500Principal("CN=Lukasz, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=PL"));

        certGen.setPublicKey(pair.getPublic());
        certGen.setSignatureAlgorithm("SHA1withDSA");

        // certGen.addExtension(X509Extensions.SubjectKeyIdentifier,
        // false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));

        //X509Certificate cert = certGen.generateX509Certificate(pair.getPrivate());

        return certGen.generateX509Certificate(pair.getPrivate(), "BC");
    }

    /**
     *
     */
    public static PKCS10CertificationRequest getCertReq() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
        String signatureAlgorithm = "SHA1withDSA";
        KeyPair keyPair = KeyGen.getKeyPair();

        //add provider
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        PKCS10CertificationRequest certReq = new PKCS10CertificationRequest(
                signatureAlgorithm,
                new X500Principal("CN=Lukasz, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=PL"),
                keyPair.getPublic(),
                null,
                keyPair.getPrivate());

        return certReq;
    }

    /**
     * zapisz cert do pliku
     */
    public static boolean saveCert(X509Certificate cert2) throws CertificateEncodingException, IOException, CertificateExpiredException, CertificateNotYetValidException, CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException, javax.security.cert.CertificateExpiredException, javax.security.cert.CertificateNotYetValidException {
        javax.security.cert.X509Certificate cert = convert2(cert2);

        FileOutputStream sigfos = null;
        try {
            sigfos = new FileOutputStream("cert.crt");
            byte[] byte_cert = cert.getEncoded();
            sigfos.write(byte_cert);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ReqGen.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {

                // st
                cert.checkValidity(new Date());
                //cert.verify(cert.getPublicKey());
/*
                 * System.out.println("Certificate Object Info: ");
                 * //System.out.println("Type = "+cert.getType());
                 * System.out.println("toString = " + cert.toString());
                 *
                 * PublicKey pubKey = cert.getPublicKey(); System.out.println();
                 * System.out.println("PublicKey Object Info: ");
                 * System.out.println("Algorithm = " + pubKey.getAlgorithm());
                 * System.out.println("Format = " + pubKey.getFormat());
                 * System.out.println("toString = " + pubKey.toString());
                 *
                 */
// st

                sigfos.close();
                return true;
            } catch (IOException ex) {
                Logger.getLogger(ReqGen.class.getName()).log(Level.SEVERE, null, ex);
                return false;
            }
        }
    }

    /**
     * wczytaj cert z pliku
     */
    public static javax.security.cert.X509Certificate getMyCert() throws CertificateExpiredException, CertificateNotYetValidException, CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException, FileNotFoundException, javax.security.cert.CertificateException {
        //System.out.println("WCZYTANIE");

        InputStream inStream = new FileInputStream("cert.crt");
        javax.security.cert.X509Certificate cert = javax.security.cert.X509Certificate.getInstance(inStream);
        return cert;
    }

    // Converts to java.security
    public static java.security.cert.X509Certificate convert(javax.security.cert.X509Certificate cert) {
        try {
            byte[] encoded = cert.getEncoded();
            ByteArrayInputStream bis = new ByteArrayInputStream(encoded);
            java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509");
            return (java.security.cert.X509Certificate) cf.generateCertificate(bis);
        } catch (java.security.cert.CertificateEncodingException e) {
        } catch (javax.security.cert.CertificateEncodingException e) {
        } catch (java.security.cert.CertificateException e) {
        }
        return null;
    }

    // Converts to javax.security
    public static javax.security.cert.X509Certificate convert2(java.security.cert.X509Certificate cert) {
        try {
            byte[] encoded = cert.getEncoded();
            return javax.security.cert.X509Certificate.getInstance(encoded);
        } catch (java.security.cert.CertificateEncodingException e) {
        } catch (javax.security.cert.CertificateEncodingException e) {
        } catch (javax.security.cert.CertificateException e) {
        }
        return null;
    }
}
